from flask import Blueprint, render_template, session, request, jsonify
from application.extentions.init_mail import mail
from flask_mail import Message
import string
import random
from concurrent.futures import ThreadPoolExecutor
import wtforms
from wtforms.validators import Email, Length, DataRequired, EqualTo
from application.modle.user import User
from application.extentions.init_sqlalchemy import db
from werkzeug.security import generate_password_hash, check_password_hash
import os

bp = Blueprint("auth", __name__, url_prefix="/")

executor = ThreadPoolExecutor(2)


def generate_verification_code(length=6):
    characters = string.ascii_uppercase + string.digits
    verification_code = random.choices(characters, k=length)
    verification_code = "".join(verification_code)
    return verification_code


def send_email(email, code):
    message = Message(subject="验证码", recipients=[email], body=code)
    mail.send(message)


@bp.route("/email/code")
def get_email_code():
    try:
        email = request.args.get("email")
        verification_code = generate_verification_code()
        session['code'] = verification_code
        executor.submit(send_email, email, verification_code)

        return jsonify({"code": 200, "message": "成功", "data": verification_code})
    except Exception as e:
        return jsonify({"code": 400, "message": "失败", "data": None})


@bp.get("/register")
def register():
    return render_template("view/register.html")


@bp.post("/register")
def register_post():
    form = RegisterForm(request.form)
    if form.validate():
        try:
            print(form)

            form.check_code()
            form.check_email(form.email)
            user = User(username=form.username.data, email=form.email.data,
                        password=generate_password_hash(form.password.data))
            db.session.add(user)
            db.session.commit()
            return jsonify({"code": 200, "message": "注册成功", "redirect_url": "/login"})
        except wtforms.ValidationError as e:
            print(e)
            return jsonify({"code": 400, "message": str(e)})
    else:
        print(form.errors)

        return jsonify({"code": 400, "message": form.errors})


# 用来检验前端提交的数据是否符合
class RegisterForm(wtforms.Form):
    email = wtforms.StringField(validators=[DataRequired(message="邮箱不能为空!"), Email(message="邮箱格式错误!")])
    code = wtforms.StringField(
        validators=[DataRequired(message="验证码不能为空!"), Length(min=6, max=6, message="验证码格式错误!")])
    username = wtforms.StringField(DataRequired(message="用户名不能为空!"),
                                   validators=[Length(min=4, max=10, message="用户名格式错误!")])
    password = wtforms.StringField(validators=[DataRequired(message="密码不能为空!"),
                                               Length(min=6, max=10, message="密码长度错误，位数必须为6至10位!")])
    password_confirm = wtforms.StringField(validators=[EqualTo("password", message="两次输入不一致")])

    # 判断验证码是否一致
    def check_code(self):
        if not self.code.data == session.get("code"):
            raise wtforms.ValidationError("验证码不一致!")

    # 判断邮箱是否被注册过
    def check_email(self, field):
        # email = field.data
        # print(email)
        # print(self.email.data )
        user = User.query.filter_by(email=field.data).first()
        if user:
            raise wtforms.ValidationError(message="该邮箱已经被注册!")


@bp.get("/login")
def login():
    return render_template("view/login.html")


@bp.post("/login")
def login_post():
    form = LoginForm(request.form)

    user = User.query.filter_by(email=form.email.data).first()
    # print()
    if user:
        if check_password_hash(user.password, form.password.data):
            return "成功"
        else:
            return jsonify({"code": 400, "message": "账号密码错误"})
    else:
        return jsonify({"code": 400, "message": "用户不存在"})


class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[DataRequired(message="邮箱不能为空")])
    password = wtforms.StringField(validators=[DataRequired(message="密码不能为空")])

    # def check_password(self,field):
    # if
